﻿//  
//  Project: SOAPI
//  http://soapics.codeplex.com
//  http://stackapps.com/questions/386
//  
//  Copyright 2010, Sky Sanders
//  Licensed under the GPL Version 2 license.
//  http://soapics.codeplex.com/license
//  
//  Date: Aug 08 2010 
//  API ver 1.0 rev 2010.0709.04
//  

#region

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows.Data;

#endregion

namespace Soapi.Contrib.ValueConverters
{
    /// <summary>
    /// See http://stackoverflow.com/questions/1281490/binding-comboboxes-to-enums-in-silverlight/1281545#1281545
    /// </summary>
    public class EnumToIEnumerableConverter : IValueConverter
    {
        private readonly Dictionary<Type, List<object>> _cache = new Dictionary<Type, List<object>>();

        #region IValueConverter Members

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var type = value.GetType();
            if (!_cache.ContainsKey(type))
            {
                var fields = type.GetFields().Where(field => field.IsLiteral);
                _cache[type] = (from field in fields
                    let a = (DescriptionAttribute[]) field.GetCustomAttributes(typeof (DescriptionAttribute), false)
                    select a.Length > 0 ? a[0].Description : field.GetValue(value)).ToList();
            }
            return _cache[type];
        }

        #endregion
    }
}
